import React, { useEffect, useState } from "react";
import { useParams, useNavigate } from "react-router-dom";
import {
  Descriptions,
  Button,
  Space,
  Table,
  Card,
  Popconfirm,
  message,
  Skeleton,
  Row,
  Col,
  Modal,
  Form,
  Input,
  Empty,
} from "antd";
import dictionaryTypesApi from "../../../apis/dictionaryTypesApi";
import dictionarysApi from "../../../apis/dictionarysApi";
import useCloseLoadingOnMount from "../../../utils/hook/useCloseLoadingOnMount";
import { hb, promptResult } from "../../../utils/common";
import ComponentHeader from "../../../components/Page/ComponentHeader";

const DictionaryTypeDetail = () => {
  useCloseLoadingOnMount();
  const { id } = useParams();
  const [loading, setLoading] = useState(true);
  const [loading2, setLoading2] = useState(false);
  const [typeDetail, setTypeDetail] = useState({});
  const [childrenData, setChildrenData] = useState([]);
  const [form] = Form.useForm();
  const [form2] = Form.useForm();
  const [open, setOpen] = useState(false);
  const [open2, setOpen2] = useState(false);
  const navigate = useNavigate();
  const [dictionaryParents, setDictionaryParents] = useState([]);

  // 列定义
  const columns = [
    {
      title: "值",
      dataIndex: "value",
      key: "value",
    },
    {
      title: "创建时间",
      dataIndex: "createTimeStr",
      key: "createTimeStr",
    },
    {
      title: "操作",
      fixed: "right",
      key: "action",
      render: (_, record) => (
        <Space size="middle">
          <Button
            type="link"
            onClick={() => setDictionaryParents([...dictionaryParents, record])}
          >
            详情
          </Button>
          <Popconfirm
            title={`你确定删除该字典"${record.value}"吗？`}
            onConfirm={() => handleDeleteDictionary(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button type="link" danger>
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  // 获取字典类别详情
  const getDictionaryTypeDetail = async () => {
    const typeRes = await dictionaryTypesApi.getDictionaryTypesDetail(id);
    if (typeRes && typeRes.status < 0) {
      navigate("/NotFound");
    }
    setTypeDetail(typeRes.data);
  };

  // 获取第一层子项（parent_id为null）
  const getSunDictionary = async () => {
    if (dictionaryParents.length > 0) {
      const childrenRes = await dictionarysApi.getSunDictionaryByParentId(
        dictionaryParents[dictionaryParents.length - 1].id
      );
      if (childrenRes.status >= 0) setChildrenData(childrenRes.data);
    } else {
      const childrenRes = await dictionarysApi.getSunDictionaryByDTId(id);
      if (childrenRes.status >= 0) setChildrenData(childrenRes.data);
    }
  };

  const bind = async () => {
    await getDictionaryTypeDetail();
    await getSunDictionary();
  };

  // 获取数据
  useEffect(() => {
    const fetchData = async () => {
      try {
        await bind();

        setLoading(false);
      } catch (error) {
        message.error("数据加载失败");
        setLoading(false);
      }
    };

    fetchData();
  }, [id]);

  useEffect(() => {
    const fetchFunc = async () => {
      setLoading2(true);
      await getSunDictionary();
      setLoading2(false);
    };
    fetchFunc();
  }, [dictionaryParents]);

  const handleAddChild = () => {
    setOpen(true);
  };

  // 编辑操作
  const handleEdit = () => {
    form2.setFieldsValue(typeDetail);
    setOpen2(true);
  };

  // 隐藏对话框
  const hideModal = () => {
    setOpen(false);
  };

  // 隐藏对话框2
  const hideModal2 = () => {
    setOpen2(false);
  };

  // 提交表单
  const addDictionary = () => {
    form.submit();
  };

  // 提交表单2
  const updateDictionaryType = () => {
    form2.submit();
  };

  // 验证后发起请求
  const onFinish = async (values) => {
    const formData = {
      ...values,
      dictionaryTypeId: id,
    };
    if (dictionaryParents.length > 0) {
      formData["parentId"] = dictionaryParents[dictionaryParents.length - 1].id;
    }
    promptResult(
      await dictionarysApi.addDictionarys(formData),
      getSunDictionary,
      () => {
        setOpen(false);
        form.resetFields();
      }
    );
  };

  // 验证后发起请求2
  const onFinish2 = async (values) => {
    promptResult(
      await dictionaryTypesApi.updateDictionaryTypes({
        ...values,
        id: id,
      }),
      getDictionaryTypeDetail,
      setOpen2
    );
  };

  // 删除字典项
  const handleDeleteDictionary = async (id) => {
    promptResult(await dictionarysApi.deleteDictionarys(id), getSunDictionary);
  };

  return (
    <div className="page-container">
      {/* 添加字典 */}
      <Modal
        title="添加字典"
        open={open}
        onOk={addDictionary}
        onCancel={hideModal}
        okText="提交"
        cancelText="取消"
      >
        <Form form={form} onFinish={onFinish}>
          <Form.Item
            name="value"
            label="值"
            rules={[{ required: true, message: "请输入字典的值" }]}
          >
            <Input placeholder="请输入字典的值" />
          </Form.Item>
        </Form>
      </Modal>
      {/* 修改字典类别 */}
      <Modal
        title="修改字典类别"
        open={open2}
        onOk={updateDictionaryType}
        onCancel={hideModal2}
        okText="提交"
        cancelText="取消"
      >
        <Form
          form={form2}
          name="editDictionaryType"
          onFinish={onFinish2}
          scrollToFirstError={true}
          labelCol={{ span: 3, offset: 0 }}
        >
          <Form.Item
            name="name"
            label="名称"
            rules={[{ required: true, message: "请输入名称" }]}
          >
            <Input placeholder="名称" />
          </Form.Item>
          <Form.Item
            name="key"
            label="键值"
            rules={[{ required: true, message: "请输入键值" }]}
          >
            <Input placeholder="键值" />
          </Form.Item>
          <Form.Item
            name="description"
            label="描述"
            rules={[{ required: true, message: "请输入描述" }]}
          >
            <Input.TextArea placeholder="描述" />
          </Form.Item>
        </Form>
      </Modal>
      {loading ? (
        <Skeleton active paragraph={{ rows: 10 }} />
      ) : (
        <Card>
          <Descriptions
            title={
              <ComponentHeader
                title={"字典类别详情"}
                extra={
                  <Button color="volcano" variant="filled" onClick={handleEdit}>
                    编辑
                  </Button>
                }
              />
            }
            bordered
            column={2}
          >
            <Descriptions.Item label="类别名称">
              {hb(typeDetail.name)}
            </Descriptions.Item>
            <Descriptions.Item label="查询键值">
              {hb(typeDetail.key)}
            </Descriptions.Item>
            <Descriptions.Item label="创建时间">
              {hb(typeDetail.createTimeStr)}
            </Descriptions.Item>
            <Descriptions.Item label="修改时间">
              {hb(typeDetail.updateTimeStr)}
            </Descriptions.Item>
            <Descriptions.Item label="描述" span={2}>
              {hb(typeDetail.description)}
            </Descriptions.Item>
          </Descriptions>

          <div style={{ marginTop: 24 }}>
            <Space
              style={{
                width: "100%",
                justifyContent: "space-between",
                marginBottom: 8,
              }}
            >
              <div
                style={{
                  padding: "8px 25px 8px 15px",
                  background: "#3498db",
                  color: "white",
                  borderTopRightRadius: "20px",
                  borderBottomRightRadius: "20px",
                }}
              >
                子项列表
                {dictionaryParents.length > 0
                  ? `(${dictionaryParents.map((d) => d.value).join(">")})`
                  : null}
              </div>
              <div>
                {dictionaryParents.length > 0 ? (
                  <Button
                    color="default"
                    variant="filled"
                    onClick={() =>
                      setDictionaryParents(
                        dictionaryParents.filter(
                          (d, i) => i < dictionaryParents.length - 1
                        )
                      )
                    }
                  >
                    返回
                  </Button>
                ) : null}
                <Button
                  color="green"
                  variant="filled"
                  onClick={handleAddChild}
                  style={{ marginRight: 8 }}
                >
                  + 新增子项
                </Button>
              </div>
            </Space>
            <Table
              loading={loading2}
              rowKey="id"
              locale={{ emptyText: <Empty description="暂无数据"></Empty> }}
              columns={columns}
              dataSource={childrenData}
              pagination={false}
              style={{ marginTop: "8px" }}
              bordered
            />
          </div>
        </Card>
      )}
    </div>
  );
};

export default DictionaryTypeDetail;
